package com.xywl.escort.view.user

import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.*
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys
import com.xywl.escort.common.PreferenceKeys.PHONE
import com.xywl.escort.common.PreferenceKeys.USER_ID
import com.xywl.escort.utils.NetworkUtil
import com.xywl.escort.utils.RegexUtils
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.GlideApp
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_modify_phone.*
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import javax.inject.Inject

@Route(path = "/xy/modify/phone")
class ModifyPhoneActivity : BaseActivity(), ModifyPhoneContract.View {
    private var isCountDown: Boolean = false
    private var captchaKey = ""
    @Inject
    lateinit var mPresenter: ModifyPhoneContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_modify_phone)
        showBackButton()
        setTitleText(R.string.setting_modify_phone)

        val phone = RxSPTool.getString(this, PHONE)
        if (!TextUtils.isEmpty(phone)) {
            text_old_phone_value.text = phone
        } else {
            ToastUtil.showTip(this, "个人信息错误，请重新登录")
            finish()
        }
        mPresenter.takeView(this)
        mPresenter.getCaptcha()
        addListener()
    }

    private fun addListener() {
        text_send_ver_code.setOnClickListener {
            getCode()
        }

        btn_confirm.setOnClickListener {
            submit()
        }

        text_send_img_code.setOnClickListener {
            mPresenter.getCaptcha()
        }
    }

    private fun getCode() {
        val phone = RxSPTool.getString(this, PHONE)
        val newPhone = edit_new_phone.text.toString().trim()
        val imgCode = edit_msg_img_code.text.toString().trim()
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error)
            return
        }
        if (!RegexUtils.checkMobile(newPhone)) {
            ToastUtil.showTip(this, R.string.user_error_hint_phone)
            return
        }
        if (!isCountDown && checkPhone(phone, newPhone) && checkCaptchaCode(imgCode)) {
            val req = GetSmsCodeReq()
            req.phone = newPhone
            req.operateType = 6
            req.captchaCode = imgCode
            req.captchaKey = captchaKey
            mPresenter.getCode(req)
        }
    }

    private fun submit() {
        val phone = RxSPTool.getString(this, PHONE)
        val newPhone = edit_new_phone.text.toString().trim()
        val code = edit_msg_ver_code.text.toString().trim()
        val imgCode = edit_msg_ver_code.text.toString().trim()
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error)
            return
        }
        if (!RegexUtils.checkMobile(phone)) {
            ToastUtil.showTip(this, R.string.user_error_hint_phone)
            return
        }
        if (checkPhone(phone, newPhone) && checkCode(code, imgCode)) {
            val req = UpdateUserPhoneReq()
            req.userId = RxSPTool.getString(this, USER_ID)
            req.oldPhone = phone
            req.newPhone = newPhone
            req.smsCode = code
            req.captchaCode = imgCode
            req.captchaKey = captchaKey
            mPresenter.updateUserPhone(req)
        }
    }

    private fun checkPhone(phone: String, newPhone: String): Boolean {
        if (phone == newPhone) {
            ToastUtil.showTip(this@ModifyPhoneActivity, R.string.user_phone_some)
            return false
        }
        return true
    }

    private fun checkCaptchaCode(imgCode: String): Boolean {
        if (TextUtils.isEmpty(imgCode)) {
            ToastUtil.showTip(this, R.string.user_img_code_empty)
            return false
        }
        return true
    }

    private fun checkCode(smsCode: String, imgCode: String): Boolean {
        if (TextUtils.isEmpty(smsCode)) {
            ToastUtil.showTip(this, R.string.user_sms_code_empty)
            return false
        }
        if (TextUtils.isEmpty(imgCode)) {
            ToastUtil.showTip(this, R.string.user_img_code_empty)
            return false
        }
        return true
    }

    private var mVerificationTimer = object : CountDownTimer((60 * 1000).toLong(), 1000) {
        override fun onTick(millisUntilFinished: Long) {
            text_send_ver_code.isEnabled = false
            text_send_ver_code.text = getString(R.string.account_auth_cd_format, millisUntilFinished / 1000)
        }

        override fun onFinish() {
            text_send_ver_code.isEnabled = true
            text_send_ver_code.text = getString(R.string.account_auth_re_get)
            isCountDown = false
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun getCaptchaSuccess(bean: CaptchaBean?) {
        Timber.e("getCaptchaSuccess")
        if (null != bean) {
            val bitmap = bean.bitmap
            captchaKey = bean.captchaKey
            GlideApp.with(this)
                    .load(bitmap)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .placeholder(R.mipmap.icon_default_picture)
                    .into(img_code)
        }
    }

    override fun getCaptchaFailure() {
        Timber.e("getCaptchaFailure")
    }

    override fun startCountDown() {
        isCountDown = true
        text_send_ver_code.isEnabled = false
        mVerificationTimer.start()
    }

    override fun getCodeFailure(msg: String?) {
        Timber.tag("ModifyPhoneActivity").e("msg=$msg")
        ToastUtil.showTip(this, msg)
    }

    override fun updateUserPhoneSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "更换绑定手机号码成功，请重新登录")
        EventBus.getDefault().post(MessageEvent(Constant.EventType.EVENT_MODIFY_LOGIN_PWD_TYPE, Constant.EventMessage.FINISH_ACTIVITY))
        clearUserInfo()
        finish()
    }

    override fun updateUserPhoneFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
        Timber.tag("ModifyPhoneActivity").e("updateUserPhoneFailure")
    }

    private fun clearUserInfo() {
        RxSPTool.clearPreference(this, USER_ID)
        RxSPTool.clearPreference(this, PreferenceKeys.TOKEN)
        RxSPTool.clearPreference(this, PHONE)
        RxSPTool.clearPreference(this, PreferenceKeys.NICK_NAME)
        RxSPTool.clearPreference(this, PreferenceKeys.HEAD_IMG)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        mVerificationTimer.onFinish()
        mVerificationTimer.cancel()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.unSubscribe()
        mVerificationTimer.onFinish()
        mVerificationTimer.cancel()
    }
}
